import {
  getMenuByToken,
  getRouters,
  login,
  logout,
  getInfo,
  register,
  forgetPassword,
  sendCode,
  phoneRegister,
  phoneLogin,
} from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import Layout from "@/layout";
import menusRouter from "@/router/modules/menus";

const state = {
  token: getToken(),
  name: "",
  avatar: "",
  introduction: "",
  roles: [],
  userInfo: {}, //用户信息
  // isShopLeader(0:店员,1:店长,2:管理员)
  permissionMenuListDatas: [], //服务端返回的菜单权限数据
  //  menusRouter: [
  //     {
  //       path: "/orderManagement",
  //       component: Layout,
  //       redirect: "/orderManagement/page",
  //       alwaysShow: true, // will always show the root menu
  //       name: "orderManagement",
  //       label: "订单管理",
  //       id: "318",
  //       meta: {
  //         title: "订单管理",
  //         icon: "lock",
  //         // roles: ['admin', 'editor'] // you can set roles in root nav
  //       },
  //       children: [
  //         {
  //           path: "addOrder",
  //           component: () => import("@/views/orderManagement/addOrder/index"),
  //           label: "新增订单",
  //           id: "319",
  //           name: "addOrder",
  //           meta: {
  //             title: "新增订单",
  //             // roles: ['admin']
  //           },
  //         },
  //       ],
  //     },

  //     {
  //       path: "/customerInformationManagement",
  //       component: Layout,
  //       redirect: "/customerInformationManagement/index",
  //       alwaysShow: true, // will always show the root menu
  //       id: "320",
  //       label: "客户管理",
  //       name: "customerInformationManagement",
  //       meta: {
  //         title: "客户管理",
  //         icon: "lock",
  //         // roles: ['admin', 'editor'] // you can set roles in root nav
  //       },
  //       children: [
  //         {
  //           path: "statistics",
  //           component: () =>
  //             import("@/views/customerInformationManagement/statistics/index"),
  //           label: "客户统计",
  //           id: "321",
  //           name: "statistics",
  //           meta: { title: "客户统计", icon: "guide", noCache: true },
  //         },
  //         {
  //           path: "customerInformation",
  //           component: () =>
  //             import(
  //               "@/views/customerInformationManagement/customerInformation/index"
  //             ),
  //           id: "322",
  //           label: "客户信息管理",
  //           name: "customerInformation",
  //           meta: { title: "客户信息管理", icon: "guide", noCache: true },
  //         },
  //       ],
  //     },
  //     {
  //       path: "/warehouseManagement",
  //       component: Layout,
  //       redirect: "/warehouseManagement/page",
  //       alwaysShow: true, // will always show the root menu
  //       label: "库存管理",
  //       id: "323",
  //       name: "warehouseManagement",
  //       meta: {
  //         title: "库存管理",
  //         icon: "lock",
  //         // roles: ['admin', 'editor'] // you can set roles in root nav
  //       },
  //       children: [
  //         {
  //           path: "statistics",
  //           component: () =>
  //             import("@/views/customerInformationManagement/statistics/index"),
  //           label: "库存统计",
  //           id: "324",
  //           name: "CustomerInformation",
  //           meta: { title: "库存统计", icon: "guide", noCache: true },
  //         },
  //         {
  //           path: "outOfStock",
  //           component: () => import("@/views/warehouseManagement/outOfStock/index"),
  //           label: "出库管理",
  //           id: "325",
  //           name: "outOfStock",
  //           meta: {
  //             title: "出库管理",
  //             // roles: ['admin']
  //           },
  //         },
  //         {
  //           path: "warehousing",
  //           component: () =>
  //             import("@/views/warehouseManagement/warehousing/index"),
  //           label: "入库管理",
  //           id: "326",
  //           name: "warehousing",
  //           meta: {
  //             title: "入库管理",
  //             // roles: ['admin']
  //           },
  //         },
  //       ],
  //     },

  //     {
  //       path: "/financialManagement",
  //       component: Layout,
  //       redirect: "/financialManagement/index",
  //       alwaysShow: true, // will always show the root menu
  //       label: "财务管理",
  //       id: "327",
  //       name: "financialManagement",
  //       meta: {
  //         title: "财务管理",
  //         icon: "money",
  //         // roles: ['admin', 'editor'] // you can set roles in root nav
  //       },
  //       children: [
  //         {
  //           path: "statistics",
  //           component: () =>
  //             import("@/views/customerInformationManagement/statistics/index"),
  //           label: "财务统计",
  //           id: "328",
  //           name: "CustomerInformation",
  //           meta: { title: "财务统计", icon: "guide", noCache: true },
  //         },
  //         {
  //           path: "income",
  //           component: () => import("@/views/financialManagement/income/index"),
  //           label: "门店收入",
  //           id: "329",
  //           name: "income",
  //           meta: { title: "门店收入", icon: "money", noCache: true },
  //         },
  //         {
  //           path: "disburse",
  //           component: () => import("@/views/financialManagement/disburse/index"),
  //           label: "门店支出",
  //           name: "disburse",
  //           id: "330",
  //           meta: { title: "门店支出", icon: "money", noCache: true },
  //         },
  //         {
  //           path: "withdraw",
  //           component: () => import("@/views/financialManagement/withdraw/index"),
  //           label: "门店提现",
  //           id: "331",
  //           name: "withdraw",
  //           meta: { title: "门店提现", icon: "money", noCache: true },
  //         },
  //         {
  //           path: "balanceRecord",
  //           component: () =>
  //             import("@/views/financialManagement/balanceRecord/index"),
  //           label: "余额记录",
  //           id: "332",
  //           name: "balanceRecord",
  //           meta: { title: "余额记录", icon: "money", noCache: true },
  //         },
  //       ],
  //     },
  //     {
  //       path: "/authorityManagement",
  //       component: Layout,
  //       redirect: "/authorityManagement/index",
  //       alwaysShow: true, // will always show the root menu
  //       label: "设置",
  //       id: "333",
  //       name: "authorityManagement",
  //       meta: {
  //         title: "设置",
  //         icon: "lock",
  //         // roles: ['admin', 'editor'] // you can set roles in root nav
  //       },
  //       children: [
  //         {
  //           path: "orderSetting",
  //           component: () => import("@/views/authorityManagement/index"),
  //           label: "订单设置",
  //           id: "334",
  //           name: "orderSetting",
  //           meta: { title: "订单设置", icon: "guide", noCache: true },
  //           redirect: "/orderSetting/page",
  //           alwaysShow: true, // will always show the root menu
  //           children: [
  //             {
  //               path: "orderSettingList",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/orderSetting/orderSettingList/index"
  //                 ),
  //               label: "配置订单",
  //               id: "335",
  //               name: "orderSettingList",
  //               meta: {
  //                 title: "配置订单",
  //                 // roles: ['admin']
  //               },
  //             },
  //           ],
  //         },
  //         {
  //           path: "/storeSetting",
  //           redirect: "/storeSetting/page",
  //           alwaysShow: true, // will always show the root menu
  //           component: () => import("@/views/authorityManagement/index"),
  //           label: "门店设置",
  //           id: "336",
  //           name: "storeSetting",
  //           meta: {
  //             title: "门店设置",
  //             icon: "lock",
  //             // roles: ['admin', 'editor'] // you can set roles in root nav
  //           },
  //           children: [
  //             {
  //               path: "product",
  //               component: () =>
  //                 import("@/views/authorityManagement/storeSetting/product/index"),
  //               label: "产品",
  //               id: "337",
  //               name: "product",
  //               meta: {
  //                 title: "产品",
  //                 // roles: ['admin']
  //               },
  //             },
  //             {
  //               path: "serviceScheme",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/storeSetting/serviceScheme/index"
  //                 ),
  //               label: "服务方案",
  //               id: "338",
  //               name: "serviceScheme",
  //               meta: {
  //                 title: "服务方案",
  //                 // roles: ['admin']
  //               },
  //             },
  //             {
  //               path: "cineraryUrn",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/storeSetting/cineraryUrn/index"
  //                 ),
  //               label: "骨灰盅",
  //               id: "339",
  //               name: "cineraryUrn",
  //               meta: {
  //                 title: "骨灰盅",
  //                 // roles: ['admin']
  //               },
  //             },
  //             {
  //               path: "weightRange",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/storeSetting/weightRange/index"
  //                 ),
  //               label: "体重区间",
  //               id: "340",
  //               name: "weightRange",
  //               meta: {
  //                 title: "体重区间",
  //                 // roles: ['admin']
  //               },
  //             },
  //           ],
  //         },
  //         {
  //           path: "permissionSetting",
  //           // component: () => import('@/views/authorityManagement/accountManagement/index'),
  //           component: () => import("@/views/authorityManagement/index"),
  //           redirect: "/permissionSetting/page",
  //           label: "权限设置",
  //           id: "341",
  //           name: "permissionSetting",
  //           meta: { title: "权限设置", icon: "guide", noCache: true },
  //           children: [
  //             {
  //               path: "accountManagement",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/permissionSetting/accountManagement/index"
  //                 ),
  //               label: "店员账号管理",
  //               id: "342",
  //               name: "accountManagement",
  //               meta: { title: "店员账号管理", icon: "guide", noCache: true },
  //             },
  //             {
  //               path: "administratorList",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/permissionSetting/administratorList/index"
  //                 ),
  //               label: "管理员列表",
  //               id: "343",
  //               name: "administratorList",
  //               meta: { title: "管理员列表", icon: "guide", noCache: true },
  //             },
  //             {
  //               path: "rolesManagement",
  //               component: () =>
  //                 import(
  //                   "@/views/authorityManagement/permissionSetting/rolesManagement/index"
  //                 ),
  //               label: "角色管理",
  //               id: "344",
  //               name: "rolesManagement",
  //               meta: { title: "角色管理", icon: "guide", noCache: true },
  //             },
  //           ],
  //         },
  //       ],
  //     },
  //  ],
  permissionIds: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USEARINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_PERMISSIONMENULIST: async (state, datas) => {
    state.permissionMenuListDatas = datas;
    let permissionIds = [];
    state.permissionIds = permissionIds;
    let isShow = null;

    function  traverseTreeDFS(nodes) {
      nodes.forEach((node) => {
        isShow = state.permissionIds.includes(Number(node.id));
        if (isShow) {
          // 处理当前节点，例如打印或进一步操作
          node.hidden = false;
          // 如果节点有子节点，递归处理它们
          if (node.children) {
            traverseTreeDFS(node.children);
          }
        } else {
          // 如果节点不可见，可以选择不进行任何操作或进行其他逻辑处理（例如标记为不显示）
          node.hidden = true;
          console.log(`Skipping ${node.text}`);
        }
      });
    }

    function traverseTreeIdDFS(node) {
      node.forEach((node) => {
        // 处理当前节点，例如打印或进一步操作
        // 如果节点有子节点，递归处理它们
        if (node.children) {
          traverseTreeIdDFS(node.children);
        }
        permissionIds.push(node.id);
      });
    }

    await   traverseTreeIdDFS(datas);
    console.log(7878, permissionIds);

  await  traverseTreeDFS(menusRouter, isShow);

    //  router.addRoutes(menusRouter)
    //  resetRouter()

    console.log("menusRouter", menusRouter, router);
  },
};

const actions = {
  //发送验证码
  sendCode({ commit }, userInfo) {
    const { phone } = userInfo;
    return new Promise((resolve, reject) => {
      sendCode({ phone: phone.trim().toString() })
        .then((response) => {
          const { data } = response;
          // commit('SET_TOKEN', data.token)
          // setToken(data.token)
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  //找回密码
  forgetPassword({ commit }, userInfo) {
    const { phone, password, code } = userInfo;
    return new Promise((resolve, reject) => {
      forgetPassword({
        phone: phone.trim(),
        userName: phone.trim(),
        password: password,
        codePhone: code,
      })
        .then((response) => {
          const { data } = response;
          // commit('SET_TOKEN', data.token)
          // setToken(data.token)
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  //phone register
  phoneRegister({ commit }, userInfo) {
    const { phone, code, password, shopName } = userInfo;
    return new Promise((resolve, reject) => {
      phoneRegister({
        phone: phone.trim(),
        password: password,
        codePhone: code,
        shopName,
      })
        .then((response) => {
          const { data } = response;
          // commit('SET_TOKEN', data.token)
          // setToken(data.token)
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  //phone login
  phoneLogin({ commit }, userInfo) {
    const { phone, code } = userInfo;
    return new Promise((resolve, reject) => {
      phoneLogin({ userName: phone.trim(), codePhone: code })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  register({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      register({ userName: username.trim(), password: password })
        .then((response) => {
          const { data } = response;
          // commit('SET_TOKEN', data.token)
          // setToken(data.token)
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       if (!response.data) {
  //         reject('Verification failed, please Login again.')
  //       }
  //  const    datas= {
  //         roles: ['admin'], // 身份
  //         introduction: 'Administrator',
  //         avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
  //         name: 'administrator',
  //         token: state.token
  //     }
  //       const { roles, name, avatar, introduction } = datas

  //       // roles must be a non-empty array
  //       // if (!roles || roles.length <= 0) {
  //       //   reject('getInfo: roles must be a non-null array!')
  //       // }
  //       commit('SET_USEARINFO', response.data)
  //   commit('SET_ROLES', roles)
  //     commit('SET_NAME', name)
  //     commit('SET_AVATAR', avatar)
  //     commit('SET_INTRODUCTION', introduction)
  //     commit('SET_TOKEN', token)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  async getInfo({ commit }) {
    return  new Promise(async (resolve, reject)  => {
      await  getMenuByToken(state.token).then((response) => {
        commit("SET_PERMISSIONMENULIST", response.data);
      });

      await  getRouters(state.token).then((response) => {});
      await  getInfo(state.token).then((response) => {
        commit("SET_USEARINFO", response.data);
        commit("SET_NAME", response.data.phone);
        // commit('SET_AVATAR', response.data.avatar)
        // commit('SET_INTRODUCTION', introduction)
      });
      const { data } = {
        data: {
          roles: ["admin"], // 身份
          introduction: "Administrator",
          avatar:
            "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
          name: "administrator",
          token: state.token,
        },
      };
      if (!data) {
        reject("Verification failed, please Login again.");
      }

      const { roles, name, avatar, introduction, token } = data;
      if (!roles || roles.length <= 0) {
        reject("getInfo: roles must be a non-null array!");
      }
      commit("SET_AVATAR", avatar);

      commit("SET_ROLES", roles);
      commit("SET_INTRODUCTION", introduction);

      commit("SET_TOKEN", token);
      resolve(data);
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit("SET_TOKEN", "");
          commit("SET_ROLES", []);
          removeToken();
          resetRouter();

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch("tagsView/delAllViews", null, { root: true });

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + "-token";

    commit("SET_TOKEN", token);
    setToken(token);

    const { roles } = await dispatch("getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch("permission/generateRoutes", roles, {
      root: true,
    });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch("tagsView/delAllViews", null, { root: true });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
